package updown.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import updown.domain.Account;
import updown.handler.ex.ParkException;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Title: com.damai.util </p>
 * <p>Description:super:jwt -  </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/3/10
 * @Version: 1.0
 */
@Slf4j
public class JwtokenUtil {


    /**
     * token秘钥
     */
    public static final String SECRET = "TESTMISTITYS";

    public static String createToken(Account account) {
        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create().withHeader(map)
        .withClaim("userName",account.getUsername())
        .withClaim("password",account.getPassword())
        .sign(Algorithm.HMAC256(SECRET));// header
        return token;
    }

    public static String getUserName(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim userName = claims.get("userName");
        if (null == userName || StringUtils.isEmpty(userName.asString())) {
            throw new ParkException("token错误，请重新登录");
        }
        return userName.asString();
    }

    //解密token
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            log.error("verifier error :{}",e);
            throw new ParkException("token错误，请重新登录");
        }
        return jwt.getClaims();
    }

    public static String getPassword(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim password = claims.get("password");
        if (null == password || StringUtils.isEmpty(password.asString())) {
            throw new ParkException("token错误，请重新登录");
        }
        return password.asString();
    }
}
